<template>
  <header class="header can-sticky">
    <div class="container">
      <div class="row">
        <div class="col-12">
          <div class="inner">
            <!-- Logo -->
            <div class="logo">
              <nuxt-link to="/" class="d-flex h-100">
                <img src="~/assets/images/logo-3.png" alt="logo" class="image-fit-contain" />
              </nuxt-link>
            </div>
            <!-- Logo -->
            <!-- Nav -->
            <TheNavigation :class="['navigation', { open: isMenuOpen }]" />
            <!-- Nav -->
            <MobileNav v-model="isMenuOpen" />
          </div>
        </div>
      </div>
    </div>
  </header>
  <div class="section-bg section-padding subheader" :style="{ backgroundImage: `url(${subheader})` }">
    <div class="container">
      <div class="row">
        <div class="col-12 text-center">
          <h2 class="text-white page-title">{{ t("nav.consulting_academy_news") }}</h2>
        </div>
      </div>
    </div>
  </div>
  <section class="section-padding section">
    <div class="container">
      <div class="row flex-lg-row-reverse">
        <NuxtLink :to="`/consulting/academy-news/${item.id}`" v-for="item in industryState.list" :key="item.id" class="col-md-6">
          <div class="post">
            <div class="post_image">
              <div class="d-flex h-100">
                <img :src="item.image_url" :alt="item.title" class="image-fit" />
              </div>
            </div>
            <div class="post_caption">
              <div class="post_date">
                {{ item.updated_at || item.created_at }}
              </div>
              <h2 class="post_title">
                <!-- 如果有详情页，可换成 NuxtLink 到 /news/[id] -->
                <div>{{ item.title }}</div>
              </h2>
            </div>
          </div>
        </NuxtLink>
        <div class="col-12">
          <nav>
            <ul class="pagination">
              <li class="page-item" :class="{ disabled: industryState.current_page === 1 }">
                <a class="page-link" href="javascript:void(0)" aria-label="Previous" @click.prevent="goTo(industryState.current_page - 1)">
                  <span aria-hidden="true">«</span>
                  <span class="sr-only">Previous</span>
                </a>
              </li>
              <li v-for="p in pages" :key="String(p)" class="page-item" :class="{ active: p === industryState.current_page, disabled: p === '…' }">
                <span v-if="p === '…'" class="page-link">…</span>
                <a v-else class="page-link" href="javascript:void(0)" @click.prevent="goTo(p as number)">{{ p }}</a>
              </li>
              <!-- Next -->
              <li class="page-item" :class="{ disabled: industryState.current_page === totalPages }">
                <a class="page-link" href="javascript:void(0)" aria-label="Next" @click.prevent="goTo(industryState.current_page + 1)">
                  <span aria-hidden="true">»</span>
                  <span class="sr-only">Next</span>
                </a>
              </li>
            </ul>
          </nav>
        </div>
      </div>
    </div>
  </section>
  <TheFooter />
  <div class="thm-bg-color-one copyright">
    <div class="container">
      <div class="row">
        <div class="col-12 text-center">
          <p class="mb-0">
            Copyright © <span id="year"></span>.
            <a target="_blank" href="#" title=" 科技创新院" class="text-white"> 科技创新院</a>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import subheader from "../assets/images/subheader.jpg";
import TheNavigation from "~/component/TheNavigation.vue";
import TheFooter from "~/component/TheFooter.vue";
import MobileNav from "~/component/MobileNav.vue";
import { getFetchData } from "~/composables/getData";

const { public: pub } = useRuntimeConfig();
const route = useRoute();
const { t } = useI18n();

useSeoMeta({
  title: "信息公开",
  description: "行业信息与西科院资讯发布，持续更新。",
  ogUrl: pub.siteUrl + route.fullPath,
  ogImage: pub.defaultOG,
});

useHead({
  script: [
    {
      type: "application/ld+json",
      children: JSON.stringify({
        "@context": "https://schema.org",
        "@type": "CollectionPage",
      }),
    },
  ],
});

const isMenuOpen = ref(false);

const industryState = reactive({
  list: [] as any[],
  page_index: 1,
  page_limit: 6,
  loading: false,
  hasMore: true,
  last_page: 1,
  current_page: 1,
  total: 0,
});

const totalPages = computed(() => industryState.last_page || Math.max(1, Math.ceil(industryState.total / (industryState.page_limit || 1))));

// 生成页码（含省略号）
const pages = computed<(number | "…")[]>(() => {
  const total = totalPages.value;
  const curr = industryState.current_page;
  const delta = 2; // 当前页左右各展示几个
  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);

  const range = new Set<number>([1, total]);
  for (let i = Math.max(1, curr - delta); i <= Math.min(total, curr + delta); i++) {
    range.add(i);
  }
  const arr = Array.from(range).sort((a, b) => a - b);
  const out: (number | "…")[] = [];
  for (let i = 0; i < arr.length; i++) {
    out.push(arr[i]);
    if (i < arr.length - 1 && arr[i + 1] - arr[i] > 1) out.push("…");
  }
  return out;
});

// 获取行业信息
const getIndustryInfo = async (page_index: number) => {
  industryState.loading = true;
  try {
    const res: any = await getFetchData({
      url: "/api/news_get_list",
      opts: { page_index, page_limit: industryState.page_limit, type: 1 },
      method: "get",
    });
    industryState.list = res.data.data;

    // 依据 total 判断是否还有更多；没有 total 就用“返回数量 < pageSize”判断
    if (typeof res?.data?.total === "number") {
      const total = res.data.total as number;
      industryState.hasMore = industryState.list.length < total;
    } else {
      industryState.hasMore = industryState.list.length === industryState.page_limit;
    }

    industryState.last_page = res.data.last_page;
    industryState.current_page = res.data.current_page;
    industryState.total = res.data.total;
  } catch (error) {
    console.log(error);
  } finally {
    industryState.loading = false;
  }
};

async function goTo(page: number) {
  if (page < 1 || page > totalPages.value || page === industryState.current_page) return;
  await getIndustryInfo(page);
}

await getIndustryInfo(industryState.page_index);
</script>
<style></style>
